package network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import hexgame.HexMove;
import hexgame.Player;;
/**
 * Peforms all communication with the remote player after the handshake 
 */
public class RemotePlayer extends Player {
	Socket socket;
	BufferedReader reader;
	PrintWriter writer;
	
	public RemotePlayer(Socket socket, BufferedReader reader, PrintWriter writer) {
		this.socket = socket;
		this.reader = reader;
		this.writer = writer;
	}
	
	@Override
	public boolean isConnected() {
		return socket.isConnected() && !socket.isClosed();
	}
	
	/**
	 * Attempts to get a move from the remote player
	 */
	@Override
	public HexMove getMove() {
		String line;
		try {
			line = reader.readLine();
			return HexNetwork.parseMove(line);
		}
		catch (IOException e) {
			return null;
		}
	}
	
	/**
	 * Sends the local player's move to the remote player
	 */
	@Override
	public void showMove(HexMove move) {
		writer.println(HexNetwork.formatMove(move.getX(), move.getY()));
	}
	
	/**
	 * We perform some simple logic on Game Over
	 */
	@Override
	public void gameOver(boolean didWin) {
		if(didWin) {
			System.out.println("Other player won game");
			writer.println("YouWin, Bye");
			try {
				socket.close();
			}
			catch (IOException e) {
				// Doesn't matter so much if the socket doesn't close properly.
			}
		}
		else {
			String line;
			try {
				line = reader.readLine();
			
				if(line.equals("YouWin, Bye")) {
					System.out.println("Confirmed Win from other client");
				}
				else
				{
					System.out.println("Other client did not confirm win");
				}
			}
			catch (IOException e) {
				System.out.println("Other client did not confirm win");
				// We just want to close the socket anyway at this point
			}
			
			try {
				socket.close();
			}
			catch (IOException e1) {
				// Doesn't matter if this fails
			}			
		}
	}
	
	@Override
	public void sendErrorMessage(String message) {
		System.out.println(message);
		try {
			writer.println("Quit");
			socket.close();
		}
		catch (IOException e) {
			// Not bothered if this fails
		}
	}

}
